﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.ComponentModel.Composition;
using ShredTheLog.Api;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Documents;
using System.Diagnostics.Contracts;
using System.Windows;

namespace ShredTheLog.ViewModels
{
    [ValueConversion(typeof(string), typeof(FlowDocument))]
    public sealed class UserDescriptionConverter : IValueConverter
    {
        [Import]
        private IShredServices ShredServices { get; set; }

        [ImportMany]
        private Lazy<ITextFormatter, IOrderMetadata>[] _formatters = null;
        private IEnumerable<ITextFormatter> Formatters
        {
            get 
            {
                Contract.Assume(_formatters != null);

                return from i in _formatters orderby i.Metadata.Order select i.Value; 
            }
        }

        public UserDescriptionConverter()
        {
            Globals.CompositionContainer.SatisfyImportsOnce(this);
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var description = (string)value;
            return new FlowDocument(new Paragraph(CreateSpan(description))) { TextAlignment = TextAlignment.Left };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        private Span CreateSpan(string description)
        {
            // Комментарии пользователя бывают пустыми (если модератор зачистил)
            //Contract.Requires(description != null);

            var embracingSpan = new Span();
            embracingSpan.DataContext = description;
            var textRun = new Run(description);
            var textSpan = new Span(textRun);
            embracingSpan.Inlines.Add(textSpan);
            Formatters.ForEach(mf => mf.Process(description, textSpan, embracingSpan));
            return embracingSpan;
        }

        public static readonly UserDescriptionConverter Default = new UserDescriptionConverter();
    }
}
